/**
 * 
 */
package com.zito.manager;

import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.downlove.common.DateUtils;
import com.downlove.common.RequestContext;
import com.downlove.database.QueryHelper;
import com.zito.ErrMsgException;
import com.zito.bean.Article;
import com.zito.bean.Articlefiles;
import com.zito.bean.Articlephotos;
import com.zito.bean.Columnz;
import com.zito.common.Paginator;
import com.zito.utils.QueryHelperExtend;

/**
 * @author YunHai-Home
 * 
 */
public class ContributeManager {

	private Paginator paginator;
	private Article article = new Article();
	private final Logger logger = LoggerFactory
			.getLogger(ContributeManager.class);

	/**
	 * 分页
	 * @return
	 */
	public String getPaginator() {
		return this.paginator.getCssPageBlock();
	}

	public Paginator getPaginatorBean() {
		return this.paginator;
	}

	/**
	 * 根据查询当前用户的所有文章投稿
	 * @param columnid
	 * @param pagesize
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<Article> ContributeListByUser(int pagesize) {
		RequestContext rc = RequestContext.get();
		Article obj = new Article();
		String filter = " `type` = 1 AND authorid = "+InteractSession.get().getUserID();
		int total = obj.TotalCount(filter);
		this.paginator = new Paginator(rc, total, pagesize);
		int totalpages = this.paginator.getTotalPages();
		int curpage = this.paginator.getCurrentPage();
		if (totalpages == 0) {
			curpage = 1;
			totalpages = 1;
		}
		List<Long> tmpList = obj.idListFilterForContribute(filter, curpage, pagesize);
		return obj.LoadList(tmpList);
	}

	/**
	 * 根据查询用户投稿列表
	 * @param columnid
	 * @param pagesize
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<Article> ContributeList(int pagesize) {
		RequestContext rc = RequestContext.get();
		Article obj = new Article();
		Long columnid = rc.param("columnid", -1L);
		String filter = " `type` = 1 ";
		if (columnid != -1L) {
			Columnz column = new Columnz().Get(columnid);//获取对象
			if (column == null || column.getType() == 0) {//对象为空，或判断type属性
				filter += " AND columnid = " + columnid;
			} else {
				filter += " AND specialid = " + columnid;
			}
		}
		int total = obj.TotalCount(filter);
		this.paginator = new Paginator(rc, total, pagesize);
		int totalpages = this.paginator.getTotalPages();
		int curpage = this.paginator.getCurrentPage();
		if (totalpages == 0) {
			curpage = 1;
			totalpages = 1;
		}
		List<Long> tmpList = obj.idListFilterForContribute(filter, curpage, pagesize);
		return obj.LoadList(tmpList);
	}
	
	/**
	 * 投稿信息刊用排行榜 （www）
	 * @return
	 */
	public List<Map<String, Object>> getContributeRankList(int pagesize) {
		return contributeRankList(pagesize);
	}
	
	/**
	 * 投稿信息刊用排行榜（互动交流）
	 * @return
	 */
	public List<Map<String, Object>> getContributeRankList() {
		return contributeRankList(-1);
	}

	/**
	 * 投稿信息刊用排行榜
	 * @param columnid
	 * @param pagesize
	 * @return
	 */
	public List<Map<String, Object>> contributeRankList(int pagesize) {
		RequestContext rc = RequestContext.get();
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		String StartDate = rc.param("startdate", "");
		String EndDate = rc.param("enddate", "");
		String filter = "";
		if(StartDate.length()>0){
			filter+=" AND auditordate >= '" + StartDate + "'";
		}
		if(EndDate.length()>0){
			filter+=" AND auditordate <= '" + EndDate + "'";
		}
		String sql = "SELECT A.uname, ifnull(B.total,0) AS total,ifnull(B.score,0) AS score " 
					+ " FROM admin A LEFT JOIN " 
						+ " (SELECT authorid,COUNT(id) AS total,SUM(score) AS score " 
						+ " FROM article WHERE `type`=1 AND `status`=2 "+filter+" GROUP BY authorid ) AS B " 
					+ " ON A.ID = B.authorid ORDER BY B.score DESC";
		if(pagesize!=-1){
			String total_sql = "SELECT COUNT(*) FROM ("+sql+") AS TEMP";
			int total = QueryHelper.count(total_sql);
			this.paginator = new Paginator(rc, total, pagesize);
			int totalpages = this.paginator.getTotalPages();
			int curpage = this.paginator.getCurrentPage();
			if (totalpages == 0) {
				curpage = 1;
				totalpages = 1;
			}
			list = QueryHelperExtend.queryListMapPage(sql, curpage, pagesize);
		}else{
			list = QueryHelperExtend.queryListMap(sql);
		}
		return list;
	}
	
	/**
	 * 获取文章详细
	 * @return
	 */
	public Article getArticle() {
		RequestContext rc = RequestContext.get();
		long id = rc.param("id", -1);
		if (id == -1)
			return article;
		return article.Get(id);
	}
	
	/**
	 * 保存投稿
	 * @return
	 * @throws ErrMsgException
	 * @throws IOException
	 */
	public boolean operatingPost() throws Exception {
		RequestContext rc = RequestContext.get();
		long tempid = rc.param("id", -1);
		return null == new Article().Get(tempid) ? insertArticle(rc) : editArticle(rc);
	}

	/**
	 * 新增投稿
	 * @param rc
	 * @return
	 * @throws ErrMsgException
	 * @throws IOException
	 */
	public boolean insertArticle(RequestContext rc) throws Exception {
		Article obj = new Article();
		obj = rc.form(Article.class);
		String error = obj.doValidator();
		if (!StringUtils.isBlank(error))
			throw new ErrMsgException(error);
		obj.setType(1);
		obj.setStatus(0);
		obj.setScore(0);
		obj.setColumnid(-1L);
		obj.setSpecialid(-1L);
		obj.setAuthorid(InteractSession.get().getUserID());
		obj.setAuthor(InteractSession.get().getUserName());
		obj.setPostdate(DateUtils.getDateTime());
		obj.setIsphoto(StringUtils.isBlank(obj.getMainphoto()) ? 0 : 1);
		return obj.Save(RequestContext.get().session().getId()) != -1L;
	}

	/**
	 * 编辑投稿
	 * @param rc
	 * @return
	 * @throws ErrMsgException
	 * @throws IOException
	 */
	public boolean editArticle(RequestContext rc) throws Exception {
		Article obj = new Article();
		obj = rc.form(Article.class);
		if (obj.getId() == -1)
			return false;
		String error = obj.doValidator();
		if (!StringUtils.isBlank(error))
			throw new ErrMsgException(error);
		obj.setIsphoto(StringUtils.isBlank(obj.getMainphoto()) ? 0 : 1);
		return obj.Update(RequestContext.get().session().getId(),
				"title", "content", "isphoto", "mainphoto", "id") != -1L;
	}

	/**
	 * 保存投稿管理
	 * @param rc
	 * @return
	 * @throws ErrMsgException
	 * @throws IOException
	 */
	public boolean SaveManageEdit() throws Exception {
		RequestContext rc = RequestContext.get();
		Article obj = new Article();
		obj = rc.form(Article.class);
		if (obj.getId() == -1)
			return false;
		String error = obj.doValidator();
		if (!StringUtils.isBlank(error))
			throw new ErrMsgException(error);
		obj.setAuditor(MasterSession.get().getUserName());
		obj.setAuditorid(MasterSession.get().getUserID());
		obj.setAuditordate(DateUtils.getDateTime());
		obj.setIsphoto(StringUtils.isBlank(obj.getMainphoto()) ? 0 : 1);
		return obj.Update(RequestContext.get().session().getId(),
				"status", "score", "columnid", "specialid", 
				"auditorid", "auditor", "auditordate",
				"title", "content", "isphoto", "mainphoto", "id") != -1L;
	}

	/**
	 * 在线投稿删除
	 * @return
	 * @throws Exception
	 */
	public boolean ContributeOnLineDelete() throws Exception {
		RequestContext rc = RequestContext.get();
		boolean re = false;
		Article article = new Article();
		Long id = rc.param("id", -1L);
		article = article.Get(id);
		if (article == null)
			return false;
		if(article.getStatus()!=0 && InteractSession.get().getUserType()==0){
			throw new Exception("该投稿已审核，如需删除请联系管理员！");
		}
		re = deleteContributeData(article);
		return re;
	}
	
	/**
	 * 在线投稿删除
	 * @return
	 * @throws Exception
	 */
	public boolean ContributeManageDelete() throws Exception {
		RequestContext rc = RequestContext.get();
		boolean re = false;
		Article article = new Article();
		Long id = rc.param("id", -1L);
		article = article.Get(id);
		if (article == null)
			return false;
		re = deleteContributeData(article);
		return re;
	}
	
	/**
	 * 删除
	 * @return
	 * @throws ErrMsgException
	 */
	public boolean deleteContributeData(Article article) throws Exception {
		boolean flag = false;
		ArticlephotosManager photo = new ArticlephotosManager();
		ArticlefilesManager file = new ArticlefilesManager();
		List<String> paths = new ArrayList<String>();
		// 首先根据ID列出所有图片数据
		List<?> photos = photo.list(article.getId().intValue());
		for (Object aphoto : photos) {
			Articlephotos tmp = (Articlephotos) aphoto;
			paths.add(tmp.getFileserverpath());
			paths.add(tmp.getThumbpath());
		}
		// 首先根据ID列出所有附件数据
		List<?> files = file.list(article.getId().intValue());
		for (Object afile : files) {
			Articlefiles tmp = (Articlefiles) afile;
			paths.add(tmp.getFileserverpath());
		}

		// 采用事务删除数据，先删除图片及附件数据，后删除该文章信息
		String deletePhoto = "DELETE FROM articlephotos WHERE articleid=?";
		String deleteFiles = "DELETE FROM articlefiles WHERE articleid=?";
		String deleteArticle = "DELETE FROM article WHERE id=?";
		try {
			QueryHelper.setAutoCommit();
			QueryHelper.commitUpdate(deletePhoto, article.getId());
			QueryHelper.commitUpdate(deleteFiles, article.getId());
			QueryHelper.commitUpdate(deleteArticle, article.getId());
			QueryHelper.commit();
			flag = true;
		} catch (Exception e) {
			flag = false;
			try {
				QueryHelper.rollback();
			} catch (SQLException e1) {
				logger.error("删除文章时出现异常：{}", e1.getMessage());
				throw new ErrMsgException("删除文章时出现异常，请联系管理员！" + e1.getMessage());
			}
			logger.error("删除文章时出现异常：{}", e.getMessage());
			throw new ErrMsgException("删除文章时出现异常，请联系管理员！" + e.getMessage());
		} finally {
			try {
				QueryHelper.closeTransConnection();
			} catch (SQLException e2) {
				logger.error("删除文章时出现异常：{}", e2.getMessage());
				throw new ErrMsgException("删除文章时出现异常，请联系管理员！" + e2.getMessage());
			}
		}
		// 数据删除成功后删除硬盘上文件,无论文件是否存在，在删除时不返回任何异常
		if (flag) {
			for (String path : paths) {
				FileUtils.deleteQuietly(new File(RequestContext.root() + path));
			}
		}
		return true;
	}
}
